package com.mooc.servlet;

import com.mooc.annotation.WebServlet;
import com.mooc.http.HttpRequest;
import com.mooc.http.HttpResponse;
import com.mooc.utils.MimeTypeUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/default")
public class DefaultServlet implements Servlet{
    @Override
    public void service(HttpRequest httpRequest, HttpResponse httpResponse) {
        try {
            String mimetype = MimeTypeUtil.getMimeType(httpRequest.getRequestUrl());
            String filePath="web" + httpRequest.getRequestUrl();
            File file=new File(filePath);
            if (file.exists()){
                FileInputStream fi = new FileInputStream("web" + httpRequest.getRequestUrl());
                byte[] data = new byte[fi.available()];
                fi.read(data);
                httpResponse.setStatusCode(200);
                httpResponse.setContentType(mimetype);
                httpResponse.write(data);
            }else {
                FileInputStream fi = new FileInputStream("web/html/404.html");
                byte[] data = new byte[fi.available()];
                fi.read(data);
                httpResponse.setStatusCode(404);
                httpResponse.setContentType("text/html;charset=utf-8");
                httpResponse.write(data);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}